using FileManager.Converters;
using FileManager.Models;
using FileManager.Services;
using FileManager.Views;
using System;
using System.IO;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows;

namespace FileManager.ViewModels
{
    public class FileDetailViewModel : BaseViewModel
    {
        private FileItem _selectedFile;
        public FileItem SelectedFile
        {
            get => _selectedFile;
            set
            {
                if (SetProperty(ref _selectedFile, value))
                {
                    LoadImagePreview();
                }
            }
        }

        private ImageSource _imagePreview;
        public ImageSource ImagePreview
        {
            get => _imagePreview;
            set => SetProperty(ref _imagePreview, value);
        }

        public ICommand OpenFileCommand { get; }
        public ICommand OpenFileLocationCommand { get; }
        public ICommand DeleteFileCommand { get; }
        public ICommand MarkAsImportantCommand { get; }
        public ICommand ViewFullImageCommand { get; }

        // 微信图片解密器实例
        private readonly DatFileDecryptor _datFileDecryptor;

        public FileDetailViewModel()
        {
            // 初始化命令 - 使用lambda表达式确保参数传递正确
            OpenFileCommand = new RelayCommand(_ => OpenFile());
            OpenFileLocationCommand = new RelayCommand(_ => OpenFileLocation());
            DeleteFileCommand = new RelayCommand(_ => DeleteFile());
            MarkAsImportantCommand = new RelayCommand(param => MarkAsImportant(param));
            ViewFullImageCommand = new RelayCommand(_ => ViewFullImage());
            
            // 初始化解密器
            _datFileDecryptor = new DatFileDecryptor();
        }

        private async void LoadImagePreview()
        {
            if (SelectedFile == null)
            {
                ImagePreview = null;
                return;
            }

            // 重置预览
            ImagePreview = null;

            // 检查是否是微信加密图片(.dat文件)
            if (Path.GetExtension(SelectedFile.FilePath).Equals(".dat", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    // 使用DatFileDecryptor解密微信.dat文件
                    var bitmapImage = await _datFileDecryptor.DecryptToBitmapImageAsync(SelectedFile.FilePath);
                    if (bitmapImage != null)
                    {
                        ImagePreview = bitmapImage;
                    }
                }
                catch (Exception ex)
                {
                    // 记录错误但不中断应用程序
                    Console.WriteLine($"解密微信图片失败: {ex.Message}");
                }
            }

            // 普通图片处理
            else if (IsImageFile(SelectedFile.FilePath))
            {
                try
                {
                    using (var fs = new FileStream(SelectedFile.FilePath, FileMode.Open, FileAccess.Read))
                    {
                        var converter = new StreamToImageConverter();
                        var imageSource = converter.Convert(fs, typeof(BitmapImage), null, System.Globalization.CultureInfo.CurrentCulture);
                        if (imageSource is BitmapImage bitmapImage)
                        {
                            ImagePreview = bitmapImage;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"加载图片失败: {ex.Message}");
                }
            }
        }

        private bool IsImageFile(string extension)
        {
            if (string.IsNullOrEmpty(extension))
                return false;

            var imageExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".ico" };
            return Array.Exists(imageExtensions, ext => ext.Equals(extension, StringComparison.OrdinalIgnoreCase));
        }

        private void OpenFile()
        {
            if (SelectedFile == null) return;

            try
            {
                // 使用系统默认程序打开文件
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                {
                    FileName = SelectedFile.FilePath,
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法打开文件：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void OpenFileLocation()
        {
            if (SelectedFile == null) return;

            try
            {
                // 打开文件所在文件夹并选中文件
                var fileInfo = new System.IO.FileInfo(SelectedFile.FilePath);
                if (fileInfo.Directory != null)
                {
                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                    {
                        FileName = "explorer.exe",
                        Arguments = $"/select,\"{SelectedFile.FilePath}\"",
                        UseShellExecute = true
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法打开文件位置：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void DeleteFile()
        {
            if (SelectedFile == null) return;

            var result = MessageBox.Show(
                $"确定要删除文件 '{SelectedFile.FileName}' 吗？\n此操作将从物理位置删除文件。",
                "确认删除",
                MessageBoxButton.YesNo,
                MessageBoxImage.Warning);

            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    System.IO.File.Delete(SelectedFile.FilePath);
                    // 这里可以添加从数据库移除文件记录的逻辑
                    MessageBox.Show("文件已删除。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                    // 清除预览
                    ImagePreview = null;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除文件失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void MarkAsImportant(object parameter)
        {
            if (SelectedFile == null || parameter == null)
                return;

            try
            {
                SelectedFile.IsImportant = (bool)parameter;
                // 这里可以添加保存到数据库的逻辑
            }
            catch { }
        }

        private void ViewFullImage()
        {
            // 查看大图逻辑
            if (ImagePreview is BitmapImage bitmapImage && SelectedFile != null)
            {
                var imageViewerWindow = new ImageViewerWindow(SelectedFile, bitmapImage);
                imageViewerWindow.ShowDialog();
            }
        }
    }
}

